package com.atguigu.day3;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo2 {
    public static void main(String[] args) {
        ReadWriteLockDemo2 readWriteLockDemo2 = new ReadWriteLockDemo2();
        readWriteLockDemo2.test2();
    }

    private ReadWriteLock rwLock = new ReentrantReadWriteLock();
    //正确写法，获取写锁之后，在释放写锁前获取读锁防止其它线程插入，确保锁降级
    public void test1() {
        rwLock.writeLock().lock();
        System.out.println("获取到写锁======开写");

        rwLock.readLock().lock();
        System.out.println("获取到读锁======开读");
        //读数据
        //可以插入其它的读线程（因为读读可并发），从而提高应用程序的执行效率
        rwLock.writeLock().unlock();
        System.out.println("释放写的锁！");

        rwLock.readLock().unlock();
        System.out.println("释放读的锁！");
    }


    //错误的锁降级示例，因为在释放写锁和获取读锁之间能够有其它的写线程插入，从而影响数据的一致性
    public void test2(){
        rwLock.writeLock().lock();
        System.out.println("======获取写锁");

        rwLock.writeLock().unlock();
        System.out.println("======释放写锁");

        //可能插入其它写线程，不能确保一定是读线程抢到锁

        rwLock.readLock().lock();
        System.out.println("======获取读锁");

        rwLock.readLock().unlock();
        System.out.println("======释放读锁");
    }
}
